<?php
/**
 * Rest File to Create a contact
 *
 */
use Shama\Messages;
use Fox\Message;
use Shama\Company\Partner;
use Shama\Company;
use Shama\Contact;
$xview = Xview::instance();

if(isset($_POST) && count($_POST) > 0)
{
	$input = $_POST;
	if(_CHARSET_ != 'UTF-8') {
		foreach($input as $key => $value)
		{
			$input[$key] = utf8_decode($value);
		}
	}
	$input['email'] = !empty($input['email']) ? $input['email'] : (!empty($input['email1']) ? $input['email1'] : null );
	$input['contactid'] = isset($input['contactid']) ? $input['contactid'] : $xview->val('contactid',$xview->val('inLineId'));
	try {

		// Handle Naming
		if(!isset($input['name1']))
		{
			$input['name1'] = $input['first_name']." ".$input['last_name'];
		}
		// Check if the company already exist in the system
		if(isset($input['company']) && !empty($input['company']))
		{
			$company = Company::findByName($input['company']);
			if(!$company->exists())
			{
				// Fill the Address data of the company with the address data
				// of the first contact
				$companyData = $input;
				$companyData['name1'] = $input['company'];
				$input['status'] = Company::STATUS_NEW;
				$company->setFields($companyData);
				$company->create();
				$default = true;
				$role = Partner::CONTACT_DEFAULT;
			}
			else
			{
				$default = false;
				$role = Partner::CONTACT_PARTNER;
			}
		}

		if(isset($input['contactid']))
		{
			try {
				$contact = \Fox\Dao::load(Contact::className(),$input['contactid']);
				$oldCompany = $contact->company();
				if(!empty($oldCompany))
				{
					$oldCompanyId = $oldCompany->companyid;
				}
			}
			catch (Fox\Object\Exception\NotExist $e)
			{
				$contact = new Contact();
			}
		}
		else
		{
			$contact = new Contact();
		}
		if(!$contact->exists())
		{
			// Create Contact
			$input['type'] = isset($input['type']) ? $input['type'] :  Contact::TYPE_LEAD;
			$input['status'] = isset($input['status']) ? $input['status'] :  Contact::STATUS_NEW;
			$input['active'] = 1;
		}
		$contact->setFields($input);
		$source = isset($input['source']) ? $input['source'] : null;
		// Manage Communication
		if(!empty($input['subject']))
		{
			$message = new Contact\Message();
			$messageData = $input;
			$messageData['cdate'] = Fox\Object::sqlDateTime(time());
			$message->setFields($input);
			$contact->addToMessages($message);
		}
		// Contact Messaging Part
		if(!$contact->exists())
		{
			$contact->create();
			if($source == 'WS_GROUP' || $source == 'WS_OFFSHORE' || $source == 'WS_SOLUTION')
			{
				// Send an Email To the Admin
				$mailer = new \Fox\Mail();
				// Sent Link Activation to the user
				$mailer->subject = Msg(Messages::BUNDLE,Messages::MAIL_NEW_CONTACT);
				$mailer->body = Msg(Messages::BUNDLE,
									Messages::MAIL_BODY_NEW_CONTACT,
									$input['name1']." ".$input['email'],
									$source,
									$input['subject'],
									$input['message']);
				$mailer->mailto = "xvilain@orinea.com;xvilain@gmail.com;nkarsenty@orinea.com;rdahbi@orinea.com";
				$mailer->tryCreate();
				//$mailer->send(false,_CHARSET_);
			}
		}
		else
		{
			$contact->prepareUpdate(Contact::CHANGE_DEFAULT);
			$contact->update();
		}
		$id = $contact->getId();

		// Add the contact to the company
		if(isset($company) && $company->exists())
		{
			$partner = new Partner();
			$partner->setFields(array("contactid" => $id,"role" => $role,"defaultflag" => $default));
			$company->replacePartners($partner);
			$companyid = $company->getId();
			if(isset($oldCompanyId))
			{
				if($oldCompanyId == $companyid)
				{
					// Do Nothing
				}
				else
				{
					$company->deleteFromPartners($oldCompany);
					$company->prepareUpdate(Company::CHANGE_ADD_PARTNER);
					$company->update();
				}
			}
			else
			{
				$company->prepareUpdate(Company::CHANGE_ADD_PARTNER);
				$company->update();
			}
		}
		
		echo json_encode(array('id' => $id));
	}
	catch(Fox\Object\Exception\Save $e)
	{
		Message::Error($e->getMessage());
		$xview->log(serialize($e),'errors.txt');
	}
	catch(\Exception $e)
	{
		Message::Error($e->getMessage());
		$xview->log(serialize($e),'errors.txt');
	}
}
else {
	Message::Error("No Data Sent");
}
echo Xview::instance()->messages(false,true);